<template>
  <div class="pro-table">
    <!-- 搜索区域 -->
    <el-card v-if="columns.some(col => col.search)" class="search-wrapper">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item 
          v-for="col in columns.filter(col => col.search)"
          :key="col.prop"
          :label="col.label"
        >
          <!-- 输入框 -->
          <el-input
            v-if="!col.searchType || col.searchType === 'input'"
            v-model="searchForm[col.prop]"
            :placeholder="`请输入${col.label}`"
            clearable
            @keyup.enter="handleQuery"
          />
          
          <!-- 选择框 -->
          <el-select
            v-else-if="col.searchType === 'select'"
            v-model="searchForm[col.prop]"
            :placeholder="`请选择${col.label}`"
            clearable
          >
            <el-option
              v-for="(opt, index) in col.options"
              :key="index"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>

          <!-- 日期选择 -->
          <el-date-picker
            v-else-if="col.searchType === 'date'"
            v-model="searchForm[col.prop]"
            type="date"
            :placeholder="`请选择${col.label}`"
            value-format="YYYY-MM-DD"
          />

          <!-- 日期范围 -->
          <el-date-picker
            v-else-if="col.searchType === 'daterange'"
            v-model="searchForm[`${col.prop}Range`]"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-wrapper">
      <!-- 工具栏 -->
      <template #header>
        <div class="toolbar">
          <div class="left">
            <slot name="toolbar-left">
              <el-button 
                v-if="showAdd" 
                type="primary" 
                :icon="Plus" 
                @click="$emit('add')"
              >
                新增
              </el-button>
              <el-button
                v-if="showBatchDelete"
                type="danger"
                :icon="Delete"
                :disabled="!selectedRows.length"
                @click="$emit('batch-delete', selectedRows)"
              >
                批量删除
              </el-button>
            </slot>
          </div>
          <div class="right">
            <slot name="toolbar-right">
              <el-tooltip content="刷新" placement="top">
                <el-button :icon="Refresh" circle @click="refreshList" />
              </el-tooltip>
              <el-tooltip content="密度" placement="top">
                <el-button :icon="Sort" circle @click="toggleSize" />
              </el-tooltip>
              <el-tooltip content="列设置" placement="top">
                <el-button :icon="SetUp" circle @click="showColumnSettings = true" />
              </el-tooltip>
            </slot>
          </div>
        </div>
      </template>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        :size="tableSize"
        v-bind="$attrs"
        @selection-change="handleSelectionChange"
      >
        <el-table-column 
          v-if="showSelection" 
          type="selection" 
          width="55" 
          align="center" 
        />
        <el-table-column 
          v-if="showIndex" 
          type="index" 
          label="序号" 
          width="60" 
          align="center" 
        />
        
        <template v-for="(col, index) in visibleColumns" :key="index">
          <el-table-column
            :prop="col.prop"
            :label="col.label"
            :width="col.width"
            :align="col.align"
            :fixed="col.fixed"
            :show-overflow-tooltip="col.tooltip"
          >
            <template #default="scope">
              <!-- 使用插槽 -->
              <slot
                v-if="col.slot"
                :name="col.slot"
                :row="scope.row"
                :prop="col.prop"
              />
              <!-- 使用渲染组件 -->
              <component
                v-else-if="col.render"
                :is="col.render"
                :row="scope.row"
                :prop="col.prop"
                v-bind="col.props || {}"
              />
              <!-- 默认显示 -->
              <span v-else>{{ scope.row[col.prop] }}</span>
            </template>
          </el-table-column>
        </template>

        <el-table-column 
          v-if="$slots.action"
          label="操作" 
          :width="actionWidth" 
          :align="actionAlign"
          :fixed="actionFixed"
        >
          <template #default="scope">
            <slot name="action" :row="scope.row" />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          :pager-count="7"
          popper-class="custom-pagination"
          prev-text="上一页"
          next-text="下一页"
          :total-text="`共 ${total} 条`"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 列设置抽屉 -->
    <el-drawer
      v-model="showColumnSettings"
      title="列设置"
      direction="rtl"
      size="300px"
    >
      <el-checkbox-group v-model="selectedColumns">
        <div 
          v-for="col in columns.filter(col => !col.hideInSetting)"
          :key="col.prop" 
          class="column-item"
        >
          <el-checkbox :label="col.prop">{{ col.label }}</el-checkbox>
        </div>
      </el-checkbox-group>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import {
  Search, Refresh, Plus, Delete,
  Sort, SetUp
} from '@element-plus/icons-vue'

const props = defineProps({
  // 列配置
  columns: {
    type: Array,
    required: true
  },
  // 表格数据
  data: {
    type: Array,
    default: () => []
  },
  // 加载状态
  loading: {
    type: Boolean,
    default: false
  },
  // 总数
  total: {
    type: Number,
    default: 0
  },
  // 是否显示序号列
  showIndex: {
    type: Boolean,
    default: true
  },
  // 是否显示选择列
  showSelection: {
    type: Boolean,
    default: false
  },
  // 是否显示新增按钮
  showAdd: {
    type: Boolean,
    default: true
  },
  // 是否显示批量删除按钮
  showBatchDelete: {
    type: Boolean,
    default: true
  },
  // 操作列宽度
  actionWidth: {
    type: String,
    default: '160'
  },
  // 操作列对齐方式
  actionAlign: {
    type: String,
    default: 'center'
  },
  // 操作列是否固定
  actionFixed: {
    type: String,
    default: 'right'
  }
})

const emit = defineEmits([
  'update:searchForm',
  'query',
  'reset',
  'add',
  'batch-delete',
  'selection-change',
  'size-change',
  'current-change',
  'refresh'
])

// 搜索表单
const searchForm = ref({})

// 表格相关
const tableData = ref(props.data)
const tableSize = ref('default')
const selectedRows = ref([])

// 分页相关
const pagination = ref({
  currentPage: 1,
  pageSize: 10
})

// 列设置相关
const showColumnSettings = ref(false)
const selectedColumns = ref(props.columns.map(col => col.prop))
const visibleColumns = computed(() => 
  props.columns.filter(col => selectedColumns.value.includes(col.prop))
)

// 监听数据变化
watch(() => props.data, (val) => {
  tableData.value = val
}, { deep: true })

// 搜索相关
const handleQuery = () => {
  pagination.value.currentPage = 1
  emit('query', {
    ...searchForm.value,
    pageNum: pagination.value.currentPage,
    pageSize: pagination.value.pageSize
  })
}

const resetQuery = () => {
  searchForm.value = {}
  handleQuery()
}

// 表格选择
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
  emit('selection-change', selection)
}

// 切换表格密度
const toggleSize = () => {
  const sizes = ['default', 'large', 'small']
  const currentIndex = sizes.indexOf(tableSize.value)
  tableSize.value = sizes[(currentIndex + 1) % sizes.length]
}

// 刷新列表
const refreshList = () => {
  emit('refresh')
}

// 分页
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  emit('size-change', val)
}

const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  emit('current-change', val)
}
</script>

<style scoped>
.pro-table {
  width: 100%;
}

.search-wrapper {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left {
  display: flex;
  gap: 10px;
}

.right {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.column-item {
  padding: 10px 20px;
  border-bottom: 1px solid #ebeef5;
}

.column-item:last-child {
  border-bottom: none;
}

:deep(.el-card__header) {
  padding: 15px 20px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 0;
}

:deep(.el-select) {
  width: 240px !important;  /* 与 el-input 保持一致的宽度 */
}

:deep(.el-input) {
  width: 240px !important;
}

:deep(.el-date-editor) {
  width: 240px !important;
}

:deep(.el-pagination) {
  --el-pagination-font-size: 14px;
  --el-text-color-primary: #606266;
}

:deep(.el-pagination .el-select .el-input) {
  width: 110px;
}

:deep(.el-pagination__sizes) {
  margin-right: 15px;
}

:deep(.el-select-dropdown__item) {
  padding: 0 15px;
}

</style> 